package mobi.greenplate.client.handler;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import mobi.greenplate.client.converter.FriendConverter;
import mobi.greenplate.client.domain.Friend;
import mobi.greenplate.client.domain.User;
import mobi.greenplate.client.converter.UserConverter;
import mobi.greenplate.client.parser.DomainHandler;

/**
 *
 * @author dmakariev
 */
public class FriendListHandler extends DomainHandler<List<Friend>> {

    private static final String FRIEND_TAG = "friend";
    private static final String FRIEND_ROOT = "//friend-list/friend";
    private static final String FRIEND_OWNER_ROOT = "//friend-list/friend/owner";
    private static final String OWNER_TAG = "owner";
    private final List<Friend> friendList = new ArrayList<Friend>();
    private Friend currentFriend;
    private User currentOwner;

    @Override
    public List<Friend> getEntity() {
        return Collections.unmodifiableList(friendList);
    }

    @Override
    public void endTag(String parentPath, String tagName, String text) {
        if (parentPath.equalsIgnoreCase(FRIEND_ROOT)) {
            currentFriend = FriendConverter.endTag(currentFriend, tagName, text);
        }
        if (parentPath.equalsIgnoreCase(FRIEND_OWNER_ROOT)) {
            currentOwner = UserConverter.endTag(currentOwner, tagName, text);
        }
    }

    @Override
    public void startTag(String parentPath, String tagName) {
        if (tagName.equalsIgnoreCase(FRIEND_TAG)) {
            currentFriend = new Friend();
            friendList.add(currentFriend);
        }
        if (tagName.equalsIgnoreCase(OWNER_TAG)) {
            currentOwner = new User();
            currentFriend.setOwner(currentOwner);
        }
    }
}
